/**
 * label-select.js
 * label select for hidden radio or checkbox
 * =======================================================
 * Author: mohanlan
 * Email: mohanlan2014@sina.com
 */

(function(root, factory) {
  if(typeof module === 'object' && module.exports) {
    module.exports = function(root, Zepto) {
      if (Zepto === undefined) {
        if (typeof window !== 'undefined') {
          Zepto = require('zepto')
        } else {
          Zepto = require('zepto')(root)
        }
      }
      factory(Zepto)
      return Zepto
    }
  } else {
    factory(root.Zepto || root.jQuery || root.$)
  }
}(this, function($) {
  'use strict'

  var LabelSelect = function(el) {
    this.$el       = $(el)
    this.$label    = this.$el.find('.label')
    this.$select = this.$el.find('.select')
    this.$wrapper = this.$el.parents(".label-select-wrapper")
  }

  LabelSelect.prototype.onSelect = function() {
    var type = this.$select.attr('type')
    if(type == 'radio') {
      this.$wrapper.find('.label').removeClass('active')
      this.$select.prop("checked", true).trigger('label:checked')
      this.$label.addClass('active')
    }else if(type == 'checkbox') {
      this.$select.prop("checked", !this.$select.prop("checked")).trigger('label:checked')
      this.$select.prop("checked") ? this.$label.addClass('active') : this.$label.removeClass('active')
    }else {
      console.log("unknow input type")
    }
  }

  LabelSelect.prototype.destroy = function() {
    $(document).off('click', tapHandler)
  }

  function Plugin() {
    return this.each(function() {
      var $this = $(this)
      var data = $this.data('label-select')
      if(!data) $this.data('label-select', (data = new LabelSelect(this)))
    })
  }

  var old = $.fn.labelSelect

  $.fn.labelSelect             = Plugin
  $.fn.labelSelect.Constructor = LabelSelect

  $.fn.labelSelect.noConflict = function() {
    $.fn.labelSelect = old
    return this
  }

  var tapHandler = function(e) {
    e.preventDefault()

    var $this = $(this)

    Plugin.call($this)

    $this.data('label-select').onSelect()
  }

  $(document)
    .on('click.tap', 'label.label-select', tapHandler)
  
}));
